package cn.zsb.zsb.ctrl;

import cn.zsb.zsb.entity.Advtise;
import cn.zsb.zsb.entity.Suser;
import cn.zsb.zsb.service.AdvtiseService;
import cn.zsb.zsb.vo.Page;
import cn.zsb.zsb.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

//import javax.servlet.ServletContext;
//import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @author oldliu
 * @since 1.0
 */
@RestController
@RequestMapping("adv")
public class AdvController {

    @Autowired
    private AdvtiseService advtiseService;

    @GetMapping("search")
    protected Page<Advtise> users(@RequestParam(name = "page", defaultValue = "1") int page,
                                  @RequestParam(name = "limit", defaultValue = "10") int limit,
                                  @RequestParam(name = "title", required = false) String title,
                                  @RequestParam(name = "url", required = false) String url,
                                  @DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(name = "starttime", required = false) Date start,
                                  @DateTimeFormat(pattern = "yyyy-MM-dd")@RequestParam(name = "end", required = false) Date end) {

        Page<Advtise> search = this.advtiseService.search(title, url, start, end, page, limit);

        //System.out.println("????????????????" + search);
        return search;
    }

    @PostMapping("add")
    public Result add(@Valid @RequestBody Advtise adv) {
        //if(adv.getSortorder()<1)
            //throw new
        //        if(adv.getTitle().length()<10)
        //            throw new RuntimeException("广告词太短了");
        this.advtiseService.add(adv);
        return Result.success("增加成功");
    }

    @Value("${images-path}")
    private String imgpath;

    @PostMapping("upload")
    public Result upload(MultipartFile file) {
        //存哪里
//        ServletContext sc = request.getServletContext();
//        String images = sc.getRealPath("images");
        String name = file.getOriginalFilename();
        String houzhui = name.substring(name.lastIndexOf('.'));
        if (!(houzhui.equals(".jpg") || houzhui.equals(".png") || houzhui.equals(".bmp")))
            return Result.error("格式" + houzhui + "不支持");
        String newName = UUID.randomUUID() + houzhui;
        try {
            file.transferTo(new File(imgpath, newName));
            return Result.success(newName, "上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("保存失败：" + e);
        }

    }
}
